package com.cg.config;

import com.cg.context.User;
import com.cg.context.UserContext;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class MyCustomFilter extends OncePerRequestFilter {

    private static final String USER_ID = "user_id";
    private static final String USER_NAME = "user_name";
    private static final String USER_PHONE = "user_phone";

    private static final String FORBIDDEN_URL = "asyncTest";

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        if(!request.getRequestURI().contains(FORBIDDEN_URL)){
            UserContext.clear();

            User user = User.builder()
                    .userId(request.getHeader(USER_ID))
                    .userName(request.getHeader(USER_NAME))
                    .userPhone(request.getHeader(USER_PHONE)).build();
            UserContext.setUser(user);
        }
        filterChain.doFilter(request, response);
    }
}
